<script setup lang="ts">
import Header from '@/components/Header/index.vue'
import Footer from '@/components/Footer/index.vue'
import SearchPart from '@/components/SearchPart/index.vue'
import CategoryBar from '@/components/CategoryBar/index.vue'
import { getNowTime, LocalStorage } from '@/utils/tools'
import Swiper from '@/components/Swiper/index.vue'
import { ref, onMounted, onUnmounted, nextTick  } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/stores/userStore'

import { getHomeData, bannerList } from '@/api/home'
import { getCategories } from '@/api/category'

const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

const scrollBar: any = ref<HTMLElement | null>(null)
const wrapper: any = ref<HTMLElement | null>(null)
const searchContainer: any = ref<HTMLElement | null>(null)
const scrollWrapper: any = ref<HTMLElement | null>(null)
const dateTimer = ref()
const currentHour = ref(0)
const token = ref(
  LocalStorage.getItem('token') ? LocalStorage.getItem('token') : ''
)
const categories = ref([])
const swiperData = ref([])

const router = useRouter()
const route = useRoute()

const isAchiveBottom = ref(false)
const showRank = ref(true)

let defaultDistant: any = null
let scrollBarPage: any = null
let scrollBarCurrentIndex = 1
let scrollContainer: any = null
let baseLength: any = null
let totalLength: any = null

const products = ref([])

const getProducts = async () => {
  const { data: res } = await getHomeData()
  if (res.code === 200) {
    const newData = res.data
      .filter((item: any) => {
        return item.content.hasStock
      })
      .map((item: any) => {
        return {
          id: item.content.id,
          productName: item.content.productName,
          salePrice: item.content.salePrice,
          saleNum: item.content.saleNum,
          stockNum: item.content.stockNum,
          brandName: item.content.brandName,
          sliderUrls: item.content.sliderUrls.split(',')[0],
        }
      })
    products.value = [...products.value, ...newData]
  }
}

const handleCategory = async () => {
  const { data: res } = await getCategories()
  // if (res.code === 200) {
  //   const formatData = JSON.parse(res.data)
  // }
  const formatData = res

  const row = Math.ceil(formatData.length / 3)
  for (let i = 0; i < row; i++) {
    const category1 = []
    const category2 = []
    const category = formatData.slice(i * 3, (i + 1) * 3).map((item: any) => {
      category1.push(item)
      category2.push(
        item.children.map((node: any) => {
            const nodes = node.children.map((child: any) => {
              return {
                id: child.id,
                name: child.name,
              }
            })
          return {
            id: node.id,
            name: node.name,
            children: nodes
          }
        })
      )
      return {
        category1,
        category2
      }
    })
    categories.value.push(category)
  }
  console.log(categories.value)
  
}

const handleSwiper = async () => {
  const { data: res } = await bannerList()
  swiperData.value = res
}

const goStore = () => {
  router.push({
    path: '/store',
  })
}

const goDetail = (title: string) => {

  router.replace({
    path: `/product`,
    query: {
      title
    }
  })
}

const login = () => {
  router.push({
    path: '/auth',
    query: {
      model: 'login',
    },
  })
}

const register = () => {
  router.push({
    path: '/auth',
    query: {
      model: 'register',
    },
  })
}

const next = () => {
  if (scrollBarCurrentIndex >= scrollBarPage) {
    return
  }
  let length = scrollWrapper.value.offsetWidth * scrollBarCurrentIndex
  if (length + baseLength > totalLength) {
    length = totalLength - baseLength
  }
  scrollContainer.style.left = `-${length}px`
  scrollBarCurrentIndex++
}

const prev = () => {
  if (scrollBarCurrentIndex <= 1) {
    return
  }
  let length = scrollWrapper.value.offsetWidth * (scrollBarCurrentIndex - 2)
  if (length < 0) {
    length = 0
  }
  scrollContainer.style.left = `-${length}px`
  scrollBarCurrentIndex--
}

const apply = () => {}

const handleScroll = () => {
  if (searchContainer.value) {
    const distant = wrapper.value.getBoundingClientRect().top
    if (distant < 0) {
      showRank.value = false
      searchContainer.value.style.position = 'fixed'
      searchContainer.value.style.top = '0'
      searchContainer.value.style.zIndex = '999'
      searchContainer.value.style.width = '100%'
      searchContainer.value.style.left = 0
      searchContainer.value.style.padding = '20px'
      searchContainer.value.style.transition = 'all .3s ease'
      searchContainer.value.style.boxShadow = '0px 1px 2px rgba(0, 0, 0, 0.1)'
    } else if (distant == defaultDistant) {
      showRank.value = true
      searchContainer.value.style.position = 'static'
      searchContainer.value.style.boxShadow = 'none'
    }
  }
  // console.log(wrapper.value.getBoundingClientRect().bottom)

  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop
  //变量windowHeight是可视区的高度
  var windowHeight =
    document.documentElement.clientHeight || document.body.clientHeight
  //变量scrollHeight是滚动条的总高度
  var scrollHeight =
    document.documentElement.scrollHeight || document.body.scrollHeight
  //滚动条到底部的条件(距底部20px时触发加载)

  if (scrollTop + windowHeight >= scrollHeight - 20 && !isAchiveBottom.value) {
    isAchiveBottom.value = true
    //延时触发数据加载
    setTimeout(() => {
      isAchiveBottom.value = false
      getProducts()
    }, 500)
  }
}

const resizeObserver = new ResizeObserver((entries) => {
  for (const entry of entries) {
    console.log(entry.target === scrollWrapper.value)

    // console.log('元素宽度大小改变：', entry.target.offsetWidth)
    if (entry.target === scrollWrapper.value) {
      if (scrollBar.value.children.length > 0) {
        console.log(scrollBar.value.children[0].offsetWidth)
        baseLength = scrollBar.value.children[0].offsetWidth
      }
      scrollBarPage = Math.ceil(totalLength / entry.target.offsetWidth)
    }
  }
})
handleSwiper()
onMounted(() => {
  if (scrollBar.value) {
    scrollContainer = document.querySelector('.scroll-bar-inner')
    scrollBar.value.style.left = '0'
    scrollBar.value.style.transition = 'left .3s ease'
    totalLength = scrollBar.value.offsetWidth
    resizeObserver.observe(scrollWrapper.value)
    defaultDistant = wrapper.value.offsetTop
    window.addEventListener('scroll', handleScroll, true)
  }
  dateTimer.value = setInterval(() => {
    clearInterval(dateTimer.value)
    const { hour } = getNowTime()
    currentHour.value = hour
  }, 1000)
  getProducts()
  handleCategory()
})

onUnmounted(() => {
  resizeObserver.disconnect()
  window.removeEventListener('scroll', handleScroll)
})
</script>

<!--  -->
<template>
  <Header />
  <div class="container flex-row">
    <div ref="wrapper" class="wrapper">
      <div ref="searchContainer" class="search-wrapper">
        <SearchPart :showRank="showRank" />
      </div>
      <div class="main flex-row">
        <div class="aside flex-col-5">
          <CategoryBar :categories="categories" />
        </div>
        <div class="main-inner flex-col-19 flex-row">
          <div class="swiper-and-other flex-col-17">
            <div class="top-bar flex-row">
              <div class="item">item1</div>
              <div class="item">item2</div>
              <div class="item">item3</div>
              <div class="item">item4</div>
              <div class="item">item5</div>
              <div class="item">item6</div>
            </div>
            <div class="ad-wrapper flex-row">
              <div class="ad-item swiper flex-col-24">
                <template v-if="swiperData.length > 0">
                  <Swiper :resources="swiperData"/>
                </template>
              </div>
            </div>
          </div>
          <div class="user-operate flex-col-7">
            <div class="user-box">
              <div class="avatar">
                <img :src="userInfo.avatar" alt="" />
              </div>
              <div class="time" v-if="token != '' && userInfo.nickName">
                {{
                  currentHour >= 18
                    ? `晚上好，${userInfo.nickName}`
                    : currentHour >= 12
                    ? `下午好，${userInfo.nickName}`
                    : currentHour >= 6
                    ? `早上好，，${userInfo.nickName}`
                    : `夜深了，，${userInfo.nickName}`
                }}
              </div>
              <div class="time" v-else>
                {{
                  currentHour >= 18
                    ? '晚上好'
                    : currentHour >= 12
                    ? '下午好'
                    : currentHour >= 6
                    ? '早上好'
                    : '夜深了'
                }}
              </div>
              <div class="operate flex-row" v-if="token == '' && !userInfo.nickName">
                <div class="operate-item" @click="login">登录</div>
                <div class="operate-item" @click="register">注册</div>
                <div class="operate-item" @click="apply">开店</div>
              </div>
            </div>
            <div class="useful-nav flex-row">
              <div class="nav-item flex-col-5">
                <img src="../../assets/vue.svg" alt="" />
                <span>常用导航</span>
              </div>
              <div class="nav-item flex-col-5">
                <img src="../../assets/vue.svg" alt="" />
                <span>常用导航</span>
              </div>
              <div class="nav-item flex-col-5">
                <img src="../../assets/vue.svg" alt="" />
                <span>常用导航</span>
              </div>
              <div class="nav-item flex-col-5">
                <img src="../../assets/vue.svg" alt="" />
                <span>常用导航</span>
              </div>
            </div>
            <div class="other-link flex-row">
              <div class="link-item flex-col-5">
                <img src="../../assets/vue.svg" alt="" />
                <span>常用导航</span>
              </div>
              <div class="link-item flex-col-5">
                <img src="../../assets/vue.svg" alt="" />
                <span>常用导航</span>
              </div>
              <div class="link-item flex-col-5">
                <img src="../../assets/vue.svg" alt="" />
                <span>常用导航</span>
              </div>
              <div class="link-item flex-col-5">
                <img src="../../assets/vue.svg" alt="" />
                <span>常用导航</span>
              </div>
              <div class="link-item flex-col-5">
                <img src="../../assets/vue.svg" alt="" />
                <span>常用导航</span>
              </div>
              <div class="link-item flex-col-5">
                <img src="../../assets/vue.svg" alt="" />
                <span>常用导航</span>
              </div>
              <div class="link-item flex-col-5">
                <img src="../../assets/vue.svg" alt="" />
                <span>常用导航</span>
              </div>
              <div class="link-item flex-col-5">
                <img src="../../assets/vue.svg" alt="" />
                <span>常用导航</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="scroll-bar">
        <div class="scroll-wrapper" ref="scrollWrapper">
          <div ref="scrollBar" class="scroll-bar-inner">
            <div class="scroll-bar-item">
              <div class="image-box">
                <img src="../../assets/vue.svg" alt="" />
              </div>
              <div class="desc-box">
                <div class="topic">运动户外</div>
                <div class="info">满300减50</div>
              </div>
            </div>
            <div class="scroll-bar-item">
              <div class="image-box">
                <img src="../../assets/vue.svg" alt="" />
              </div>
              <div class="desc-box">
                <div class="topic">运动户外</div>
                <div class="info">满300减50</div>
              </div>
            </div>
            <div class="scroll-bar-item">
              <div class="image-box">
                <img src="../../assets/vue.svg" alt="" />
              </div>
              <div class="desc-box">
                <div class="topic">运动户外</div>
                <div class="info">满300减50</div>
              </div>
            </div>
            <div class="scroll-bar-item">
              <div class="image-box">
                <img src="../../assets/vue.svg" alt="" />
              </div>
              <div class="desc-box">
                <div class="topic">运动户外</div>
                <div class="info">满300减50</div>
              </div>
            </div>
            <div class="scroll-bar-item">
              <div class="image-box">
                <img src="../../assets/vue.svg" alt="" />
              </div>
              <div class="desc-box">
                <div class="topic">运动户外</div>
                <div class="info">满300减50</div>
              </div>
            </div>
            <div class="scroll-bar-item">
              <div class="image-box">
                <img src="../../assets/vue.svg" alt="" />
              </div>
              <div class="desc-box">
                <div class="topic">运动户外</div>
                <div class="info">满300减50</div>
              </div>
            </div>
            <div class="scroll-bar-item">
              <div class="image-box">
                <img src="../../assets/vue.svg" alt="" />
              </div>
              <div class="desc-box">
                <div class="topic">运动户外</div>
                <div class="info">满300减50</div>
              </div>
            </div>
            <div class="scroll-bar-item">
              <div class="image-box">
                <img src="../../assets/vue.svg" alt="" />
              </div>
              <div class="desc-box">
                <div class="topic">运动户外</div>
                <div class="info">满300减50</div>
              </div>
            </div>
            <div class="scroll-bar-item">
              <div class="image-box">
                <img src="../../assets/vue.svg" alt="" />
              </div>
              <div class="desc-box">
                <div class="topic">运动户外</div>
                <div class="info">满300减50</div>
              </div>
            </div>
            <div class="scroll-bar-item">
              <div class="image-box">
                <img src="../../assets/vue.svg" alt="" />
              </div>
              <div class="desc-box">
                <div class="topic">运动户外</div>
                <div class="info">满300减50</div>
              </div>
            </div>
            <div class="scroll-bar-item">
              <div class="image-box">
                <img src="../../assets/vue.svg" alt="" />
              </div>
              <div class="desc-box">
                <div class="topic">运动户外</div>
                <div class="info">满300减50</div>
              </div>
            </div>
            <div class="scroll-bar-item">
              <div class="image-box">
                <img src="../../assets/vue.svg" alt="" />
              </div>
              <div class="desc-box">
                <div class="topic">运动户外</div>
                <div class="info">满300减50</div>
              </div>
            </div>
            <div class="scroll-bar-item">
              <div class="image-box">
                <img src="../../assets/vue.svg" alt="" />
              </div>
              <div class="desc-box">
                <div class="topic">运动户外</div>
                <div class="info">满300减50</div>
              </div>
            </div>
          </div>
        </div>
        <div class="scroll-left-btn" @click="prev">
          <i class="iconfont icon-jiantouzuo"></i>
        </div>
        <div class="scroll-right-btn" @click="next">
          <i class="iconfont icon-jiantouyou"></i>
        </div>
      </div>
      <div class="product-container flex-row">
        <div
          class="product-item-wrap default"
          v-for="(item, index) in products"
          :key="index"
        >
          <div class="product-item" @click="goDetail(item.productName)">
            <div class="product-img">
              <img :src="item.sliderUrls" alt="" />
            </div>
            <div class="product-info">
              <div class="info-title-wrapper">
                <div class="info-title">
                  {{ item.productName }}
                </div>
              </div>
              <div class="tag-list">
                <div class="tag-text">大疆</div>
                <div class="tag-text">无人机</div>
                <div class="tag-text">送运费险</div>
                <div class="tag-text">淘金币减3.9元</div>
              </div>
              <div class="price-wrapper">
                <span class="price-unit">￥</span>
                <span class="price-value">{{ item.salePrice }}</span>
                <span class="month-sale" v-if="item.saleNum > 0"
                  >{{ item.saleNum }}+人购买</span
                >
              </div>
              <div class="store-wrapper">
                <div class="store-name" @click.stop="goStore()">
                  {{ item.brandName }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <Footer />
</template>

<style lang="less" scoped>
.container {
  padding: 10px;
  background-color: #e9e9e9;
  justify-content: center;
  .search-wrapper {
    // position: fixed;
    // top: 0;
    // z-index: 999;
    // width: 100%;
    // left: 0;
    box-sizing: border-box;
    padding: 20px 0 20px 0;
    background-color: var(--mode-bg);
  }
  .wrapper {
    background-color: #fff;
    width: 1296px;
    border-radius: 10px;
    box-sizing: border-box;
    padding: 20px;
  }
  .main-inner {
    padding-left: 20px;
    box-sizing: border-box;
  }
}
.swiper-and-other {
  box-sizing: border-box;
  padding-right: 20px;
  display: flex;
  flex-direction: column;
  .ad-wrapper {
    flex-grow: 1;
    margin-top: 20px;
  }
}
.top-bar {
  width: 100%;
  height: 48px;
  border-radius: 10px;
  background-color: #f3f6f8;
  .item {
    position: relative;
    flex-grow: 1;
    line-height: 48px;
    text-align: center;
    cursor: pointer;
    color: #ff0036;
  }
}

.item:not(:last-child)::after {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translate(0, -50%);
  content: '|';
  color: #d9d9d9;
}

.ad-item {
  overflow: hidden;
}

.ad-item.swiper {
  overflow: hidden;
  border-radius: 10px;
}

.user-box {
  width: 100%;
  box-sizing: border-box;
  .avatar {
    padding-top: 1px;
    width: 100%;
    height: 76px;
    display: flex;
    justify-content: center;
    align-items: center;
    img {
      width: 76px;
      height: 76px;
      border-radius: 50%;
      border: 1px solid;
    }
  }
  .time {
    width: 100%;
    height: 36px;
    line-height: 36px;
    text-align: center;
    margin: 12px 0;
  }
  .operate {
    height: 48px;
    justify-content: space-evenly;
    .operate-item {
      width: 72px;
      height: 48px;
      text-align: center;
      line-height: 48px;
      font-weight: bold;
      border-radius: 10px;
      cursor: pointer;
      &:not(:last-child) {
        color: #fff;
      }
      &:nth-of-type(1) {
        background-color: #ff6408;
      }
      &:nth-of-type(2) {
        background-color: #feb306;
      }
      &:nth-of-type(3) {
        background-color: #f4f6f8;
      }
    }
  }
}
.useful-nav {
  // box-sizing: border-box;
  padding: 20px 0;
  justify-content: space-between;
  .nav-item {
    display: flex;
    margin-top: 10px;
    flex-direction: column;
    align-items: center;
    .nav-icon {
      width: 48px;
      height: 48px;
      border-radius: 50%;
      background-color: #f4f6f8;
      margin-bottom: 12px;
    }
    span {
      font-size: @small-font-size;
      line-height: 18px;
    }
  }
}

.other-link {
  flex-wrap: wrap;
  justify-content: space-between;
  .link-item {
    display: flex;
    margin-top: 10px;
    flex-direction: column;
    align-items: center;
    .link-icon {
      width: 48px;
      height: 48px;
      border-radius: 50%;
      background-color: #f4f6f8;
      margin-bottom: 12px;
    }
    span {
      font-size: @small-font-size;
      line-height: 18px;
    }
  }
}

.scroll-bar-inner {
  display: flex;
  position: absolute;
  // flex-shrink: 0;
  left: 0px;
  transition: all 0.3s ease;
}

.scroll-bar {
  margin-top: 20px;
  width: 100%;
  padding: 10px 0;
  // background: #afe;
  border-radius: 10px;
  box-sizing: border-box;
  background-color: #f3f6f8;
  position: relative;
  height: 88px;
  padding: 10px;
  box-shadow: inset 0px 0px 3px rgba(0, 0, 0, 0.1),
    inset 0px 0px 3px rgba(0, 0, 0, 0.1), inset 0px 0px 3px rgba(0, 0, 0, 0.1),
    inset 0px 0px 3px rgba(0, 0, 0, 0.1), inset 0px 0px 3px rgba(0, 0, 0, 0.1);
  .scroll-wrapper {
    width: 100%;
    height: 100%;
    overflow: hidden;
    position: relative;
  }
  .scroll-bar-item {
    display: flex;
    width: 176px !important;
    align-items: center;
    cursor: pointer;
    position: relative;
    padding: 10px;
    border-radius: 10px;
    background-color: #fff;
    box-shadow: 0px 0px 3px rgba(0, 0, 0, 0.2);
    &:not(:last-child) {
      margin-right: 10px;
    }
    .image-box {
      width: 48px;
      height: 48px;
      margin-right: 10px;
      overflow: hidden;
      border-radius: 50%;
      background-color: #000;
    }
    img &:not(:last-child) {
      margin-right: 10px;
    }
    .image-box {
      width: 48px;
      height: 48px;
      margin-right: 10px;
      overflow: hidden;
      border-radius: 50%;
      background-color: #000;
    }
    img {
      width: 100%;
      display: inline-block;
    }
  }
  .desc-box {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;
  }
  .topic {
    font-size: 14px;
    line-height: 24px;
  }
  .info {
    font-size: @small-font-size;
    color: #666;
  }
  .scroll-left-btn,
  .scroll-right-btn {
    position: absolute;
    background-color: #fff;
    width: 24px;
    height: 24px;
    line-height: 24px;
    border-radius: 50%;
    text-align: center;
    border: 1px solid #d9d9d9;
    cursor: pointer;
    color: #999;
    box-shadow: @shadow-color;
  }
  .scroll-left-btn {
    left: -1%;
    top: 50%;
    transform: translateY(-50%);
  }
  .scroll-right-btn {
    right: -1%;
    top: 50%;
    transform: translateY(-50%);
  }
}

.product-container {
  box-sizing: border-box;
  margin-top: 10px;
  flex-wrap: wrap;
}
.product-item-wrap.default {
  box-sizing: border-box;
  padding: 10px;
  width: 20%;
  .product-item {
    padding: 10px;
    border-radius: 10px;
    overflow: hidden;
    // box-shadow: @shadow-color;
    transition: all 0.3s;
    &:hover {
      transform: translateY(-5px);
      box-shadow: @shadow-color;
    }
  }
  .product-img {
    width: 100%;
    height: 230px;
    border-radius: 10px;
    background-color: yellow;
    img {
      width: 100%;
      height: 100%;
      border-radius: 10px;
    }
  }
  .info-title {
    font-size: 14px;
    line-height: 20px;
    height: 40px;
    overflow: hidden;
    margin: 10px 0;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  .tag-list {
    display: flex;
    box-sizing: border-box;
    padding: 0 2px;
  }
  .tag-text {
    color: #ff5000;
    font-size: 12px;
    &:not(:last-child) {
      margin-right: 5px;
    }
  }
  .price-wrapper {
    margin: 10px 0;
    display: flex;
    align-items: flex-end;
    flex-direction: row;
    height: 24px;
  }
  .price-unit,
  .price-value {
    color: #ff5000;
  }
  .price-unit {
    font-size: 14px;
    line-height: 14px;
    margin-bottom: 1px;
    margin-right: 2px;
  }
  .price-value {
    font-size: 24px;
    font-weight: 700;
    line-height: 24px;
  }
  .month-sale {
    color: #50607a;
    font-size: 14px;
    line-height: 14px;
    margin-bottom: 1px;
    margin-left: 8px;
  }
  .store-wrapper {
    display: flex;
    cursor: pointer;
    .store-name {
      font-size: 12px;
      line-height: 18px;
    }
  }
}

@media screen and (max-width: 1276px) {
  .product-item-wrap.default {
    width: 25%;
  }
}

@media screen and (max-width: 1239px) {
  .aside {
    display: none;
  }
  .container .wrapper {
    width: 100%;
  }
  .main-inner.flex-col-19 {
    padding: 0;
    max-width: calc(4.16667 * 24%);
    flex: 0 0 calc(4.16667 * 24%);
  }
  .main {
    width: 100%;
  }
}

@media screen and (max-width: 1032px) {
  .product-item-wrap.default {
    width: 33.3%;
  }
}

@media screen and (max-width: 868px) {
  .swiper-and-other {
    padding: 0;
    height: 436px;
    margin-bottom: 20px;
    max-width: calc(4.16667 * 24%);
    flex: 0 0 calc(4.16667 * 24%);
  }
  .user-operate {
    max-width: calc(4.16667 * 24%);
    flex: 0 0 calc(4.16667 * 24%);
  }
  .main-inner.flex-col-19 {
    flex-wrap: wrap;
  }
}

@media screen and (max-width: 788px) {
  .product-item-wrap.default {
    width: 50%;
  }
}

@media screen and (max-width: 640px) {
  .container {
    padding: 10px 0;
    border-radius: 0;
  }
  .container .wrapper {
    border-radius: 0;
  }
}

@media screen and (max-width: 544px) {
  .product-item-wrap.default {
    width: 100%;
    padding: 0;
  }
}
</style>
